import time
import traceback

import cv2
from py_base.tools import win32, img
from src import enum, predict, shot

def do():
    hwnd = win32.findWindows(enum.setting['win_title'])
    if not hwnd:
        raise Exception("找不到窗口")

    t = time.time()
    while True:
        if not enum.predicting:
            print("退出预测")
            break
        # 记录该帧开始处理的时间
        start_time = time.time()

        image, hwnd = img.getScreenshot(hwnd)
        enum.new_pic = image
        # cv2.imwrite("out/{%d}aa.png" % time.time_ns(), image)
        frame = image.copy()
        if predict.is_boss():
            shot.click()
        elif enum.setting['auto_shot']:
            frame, target, shot_point = predict.process_frame(frame)
            if target is not None and shot_point is not None:
                shot.shot(target, shot_point)

        if enum.setting['auto_reload'] and predict.get_zhuang():
            shot.zhuang()

        # 记录该帧处理完毕的时间
        end_time = time.time()
        # 计算每秒处理图像帧数FPS
        FPS = 1 / max((end_time - start_time), 0.01)
        # 在画面上写字：图片，字符串，左上角坐标，字体，字体大小，颜色，字体粗细
        FPS_string = 'FPS  ' + str(int(FPS))  # 写在画面上的字符串
        frame = cv2.putText(frame, FPS_string, (25, 60), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255, 0, 255), 2)

        if enum.setting['resize'] != 1:
            frame = cv2.resize(frame, None, fx=enum.setting['resize'], fy=enum.setting['resize'], interpolation=cv2.INTER_LINEAR)


        cv2.imshow('my_window %s' % t, frame)
        if cv2.waitKey(5) == ord('q'):
            enum.main_window.setPredict(False)
            break
def begin():
    try:
        do()
    except Exception as e:
        enum.main_window.info.setText(str(e))
        enum.main_window.setPredict(False)
        print('str(Exception):\t', str(Exception))
        print('traceback.print_exc():')
        traceback.print_exc()
        print('traceback.format_exc():\n%s' % traceback.format_exc())
